package com.ym.controller.admin;


import com.ym.common.constant.Coder;
import com.ym.core.config.ConfigCenterProperties;
import com.ym.core.config.YunxinConfig;
import com.ym.core.domain.APIResponse;
import com.ym.core.domain.BaseController;
import com.ym.core.shiro.ShiroTokenManager;
import com.ym.core.shiro.ShiroUtil;
import com.ym.core.shiro.token.SysToken;
import com.ym.medical.domain.vo.PCLoginVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * Description:
 *
 * @Author: wenbo
 * Date: 2020-08-18
 * Time: 9:12
 */

@Api(tags = "admin-登录")
@Controller
public class LoginController extends BaseController {
	private static final Logger LOGGER = LoggerFactory.getLogger(LoginController.class);


	@Autowired
	private ConfigCenterProperties configCenterProperties;


	@ApiOperation("用户登录")
	@PostMapping(value = "/ajaxLogin", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
	@ResponseBody
	public APIResponse submitLogin(
			@ApiParam(name = "loginVo", value = "账号", required = true)
			@RequestBody PCLoginVo loginVo) {
		Subject subject = SecurityUtils.getSubject();
		String code = loginVo.getCode();
		SysToken token = new SysToken(code, loginVo.getPwd());
		subject.login(token);
		ShiroTokenManager.bindUserToken();
		YunxinConfig yunxinConfig = configCenterProperties.getYunxinConfig();
		Map<String, Object> result = new LinkedHashMap<>();
		result.put("user", ShiroUtil.getLoginUser());
		result.put("appKey", yunxinConfig.getAppKey());
		result.put("accid", yunxinConfig.getCustomerAccid());
		result.put("token", yunxinConfig.getCustomerToken());
		result.put("sessionId", ShiroUtil.getSession().getId());
		result.put("menuList", ShiroUtil.getSession().getAttribute("menuList"));
		return successData(result);
	}

	/**
	 * 退出登录
	 *
	 * @return
	 */
	@ApiOperation("退出登录")
	@GetMapping("/logOut")
	@ResponseBody
	public APIResponse logOut() {
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		return successMsg("退出成功");
	}

	/**
	 * 未登录，shiro应重定向到登录界面，此处返回未登录状态信息由前端控制跳转页面
	 *
	 * @return
	 */
	@GetMapping(value = "/unAuth")
	@ResponseBody
	public APIResponse unAuth() {
		return failCode(Coder.Login.NO_LOGIN);
	}
}
